package org.jeecg.modules.network.network.tcp;

import com.alibaba.fastjson.JSON;
import com.zhouwr.common.message.DeviceMessage;
import com.zhouwr.common.message.Message;
import com.zhouwr.common.network.DeviceMessageCodec;
import com.zhouwr.common.network.TcpConnectContext;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.network.network.NetworkConnectStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.SocketAddress;

/**
 * Tcp服务器接收处理程序
 *
 * @author zhouwenrong
 * @date 2020/02/23 21:08
 */
@Slf4j
@Component
public class TcpServerReceiveHandler extends ChannelInboundHandlerAdapter {

    private static TcpServerReceiveHandler receiveHandler;

    @Autowired
    private ApplicationEventPublisher publisher;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object object) throws Exception {
        log.debug(">>>>> Tcp服务器接收处理程序 >>> TcpServerReceiveHandler <<<<<<");

        try {
            SocketAddress deviceAddress = ctx.channel().remoteAddress();
            // 根据设备地址拿到设备上下文信息
            TcpConnectContext tcpConnectContext = (TcpConnectContext) NetworkConnectStore.getNetworkConnect(deviceAddress);
            // 获取数据解析器
            DeviceMessageCodec messageCodec = tcpConnectContext.getMessageCodec();
            log.info("消息编解码器：{}", JSON.toJSON(messageCodec));
            Message decode = messageCodec.decode(tcpConnectContext, object);
            log.info("解码之后数据：{}，{}", decode.getClass().getName(), JSON.toJSONString(decode));

            DeviceMessage deviceMessage = (DeviceMessage) decode;
            receiveHandler.publisher.publishEvent(deviceMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @PostConstruct
    public void init() {
        receiveHandler = this;
        receiveHandler.publisher = this.publisher;
    }
}
